<?php
/**
 * @author Inhere
 * @version v1.0
 * Use : this
 * Date : 2015-1-10
 * file: Identify.php
 */

namespace ulue\parts\auth;

use Ulue;
use ulue\core\abstracts\AbstractCore;
use ulue\parts\security\Token;

class Identify extends AbstractCore
{

    protected $_key            = 'lkjdfdouerdsdfxcg';
    // private $_isLoginKey     = 'isLogin';

    /**
     * expires (minutes)
     */
    public $expires = '20';

    public $loginUrl = '/site/login';

    public $returnUrl;

    public $logoutShowUrl = '/';

    public function __construct(array $options=[])
    {
        if ($options) {
            $this->bind($options);
        }
    }

    public function bind(array $options)
    {
        foreach ($options as $attr => $value) {
            if (property_exists($this, $attr)) {
                $this->$attr = $value;
            }
        }

        return $this;
    }

    public function setReturnUrl($value)
    {
        $this->returnUrl = trim($value);

        return $this;
    }
    public function getReturnUrl()
    {
        if ( !$this->returnUrl ) {
            $url = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : \Ioc::get('app.uri')->get('home.url');

            $this->returnUrl = $url;
        }

        return $this->returnUrl;
    }

    /**
     * 退出登录后显示的页面地址, 默认跳到首页
     */
    public function getLogoutShowUrl()
    {
        if ( !$this->logoutShowUrl ) {
            return $this->loginUrl;
        }

        return $this->logoutShowUrl;
    }

    public function getSecureKey()
    {
        return Token::md5($this->_key);
    }

    public function setKey($value)
    {
        $this->_key = (string)$value;

        return $this;
    }

    public function getKey()
    {
        return $this->_key;
    }

    #
    public function login(array $data)
    {
        $key    = $this->getSecureKey();

        $info = [
            $key                => serialize($data),
            'start.active.time' => time(),
            'isLogin'           => '1',
            // 'token'             => crypt($data['id']),
        ];

        return $this->set($setInfo);
    }

    public function verfiy()
    {

    }

    public function getAll()
    {
        return Ulue::$app->session->get( $this->getSecureKey() );
    }

    public function get($name)
    {
        $name = trim($name);
        $data = Ulue::$app->session->getAll();
        $data = unserialize($data);

        return array_key_exists($name, $data) ? $data[$name] : false;
    }

    public function set($name, $value )
    {
        if( $name ) {
            Ulue::$app->session->set( $name , $value );
        }

        return $this;

    }

    public function logout()
    {
        if ( Ulue::$app->session->destroy() ) {

            Ulue::$app->controller->doneJump('/', [
                    'msg'       => 'GoodBye!',
                    'time'      => '3',
                    'btnText'   => '立即跳转',
                ]);
        } else {
            throw new \DRuntimeException("has Error!!" );
        }
    }

    /**
     * updateActiveTime 检查登录时间是否超时]
     * @return [type] [description]
     */
    private function _checkLoginTimeout()
    {
        $lastActiveTime = Ulue::$app->session->get('start.active.time');

        // 没超时 更新活动时间起点...
        if ( !isLoginTimeout($lastActiveTime) )
        {
            Ulue::$app->session->set('start.active.time', time());

            return true;
        }

        $this->reLogin();

        return false;
    }

    /**
     * 是否登陆超时 超时 true 未超时 false
     * @return bool
     */
    public function isLoginTimeout($lastActiveTime)
    {
        if (!$lastActiveTime || !is_integer($lastActiveTime)) {
            return true;
        }

        $timeDifference = time()-$lastActiveTime;

        return $timeDifference > ($this->expires * 60);
    }

    public function reLogin()
    {
        Ulue::$app->getController()->doneJump($this->loginUrl, [
                    'msg'       => 'Login timeout, please login again!',
                    'time'      => '3',
                    'btnText'   => '立即跳转',
                ]);
    }

    public function getIsLogin()
    {
        if ('1' === Ulue::$app->session['isLogin'] ) {

            return $this->_checkLoginTimeout();
        }

        return false;
    }

    public function __get($name)
    {
        if ( ($value = $this->get($name)) !== false ) {

            return $value;
        }

        return parent::__get($name);
    }
}
